const fs = require('fs')
const { version } = require('os')
const path = require('path')

/**
 * @param {String} folderPath 文件夹路径
 * @param {String} folderName 文件夹名称
 * @param {String} saveFolderPath 生成的新文件要存放在哪（文件夹）
 * @param {String} versionData 要执行替换的版本数据
 */
const replaceVersion = (folderPath, folderName, saveFolderPath, versionData) => {
  const files = fs.readdirSync(folderPath)
  if (files.length) {
    const promises = files.map(
      (fileName) =>
        new Promise((resolve, reject) => {
          console.log('文件名', fileName)
          const filePath = path.join(folderPath, '/' + fileName)
          const stat = fs.statSync(filePath)
          if (stat.isFile()) {
            // 如果是文件
            fs.readFile(filePath, function (err, data) {
              if (err) {
                reject(err)
              }
              let str = data.toString()
              str = str.replace(/\{\{version\}\}/g, versionData.version)
              str = str.replace('{{versionTime}}', versionData.versionTime)
              str = str.replace('{{updateinfo}}', versionData.remarks)

              if (folderName === 'wyt' && fileName === 'list.html') {
                str = str.replace('{{appendVersion}}', `<li><a href="../wyt${versionData.version}/index.html">版本 ${versionData.version}</a></li>`)
              }

              let newFoldName = folderName
              if (folderName === 'version') {
                newFoldName = `wyt${versionData.version}`
              }
              const newFoldPath = path.join(saveFolderPath, `/${newFoldName}`)
              if (!fs.existsSync(newFoldPath)) {
                fs.mkdirSync(newFoldPath)
              }
              const newPath = path.join(saveFolderPath, `/${newFoldName}/`, fileName)
              fs.writeFileSync(newPath, str)
              resolve()
              // fs.writeFile(newPath, str, function (err1) {
              //   if (err1) reject(err)
              //   resolve()
              // })
            })
          } else {
            resolve()
          }
        })
    )
    return new Promise((resolve, reject) => {
      return Promise.all(promises).then(resolve, reject)
    })
  }
  return Promise.resolve()
}

function updateListTemplate(templateFolder, versionData) {
  const filePath = path.join(templateFolder, '/wyt/list.html')
  fs.readFile(filePath, function (err, data) {
    let str = data.toString()
    if (str.indexOf(versionData.version) < 0) {
      str = str.replace('{{appendVersion}}', `{{appendVersion}}<li><a href="../wyt${versionData.version}/index.html">版本 ${versionData.version}</a></li>`)
      fs.writeFileSync(filePath, str)
    }
  })
}

/**
 * 递归删除文件夹(同步方式)
 * @param {String} path 文件夹路径
 */
function deleteFolder(path) {
  var files = []
  try {
    if (fs.existsSync(path)) {
      files = fs.readdirSync(path)
      files.forEach(function (file, index) {
        var curPath = path + '/' + file
        if (fs.statSync(curPath).isDirectory()) {
          // recurse
          deleteFolder(curPath)
        } else {
          // delete file
          fs.unlinkSync(curPath)
        }
      })
      fs.rmdirSync(path)
    }
  } catch (err) {
    console.log(err)
  }
}

module.exports = {
  replaceVersion,
  deleteFolder,
  updateListTemplate
}
